package service

import (
	sqlc "bgs/db/sqlc"
	"bgs/util"
	"context"
	"fmt"
)

type ListNormalProductWithDistributeInfoPtrsParam struct {
	ProductGroupID int64
	Keyword        string
}

// ListNormalProductWithDistributeInfoPtrsOfBrandByBrandID
func (s *ProductServiceImp) ListNormalProductWithDistributeInfoPtrsOfBrand(ctx context.Context, q *sqlc.Queries, brandID int64, pagerPtr *util.Pager, ptr *ListNormalProductWithDistributeInfoPtrsParam) (total int64, ptrs []*sqlc.ListNormalProductWithDistributeInfosByBrandIDRow, err error) {
	ts := pagerPtr.Ts
	productGroupID := ptr.ProductGroupID
	keyword := ptr.Keyword
	isKeywordEmpty := util.IsEmpty(keyword)
	keywordLike := fmt.Sprintf("%%%s%%", keyword)

	total, err = q.CountNormalProductsByBrandID(ctx, sqlc.CountNormalProductsByBrandIDParams{
		Created:        ts,
		BrandID:        brandID,
		ProductGroupID: productGroupID,
		IsKeywordEmpty: isKeywordEmpty,
		Keyword:        keywordLike,
	})
	if err != nil {
		return
	}
	if total == 0 {
		// 不用继续调用listfunc
		return
	}
	rows, err := q.ListNormalProductWithDistributeInfosByBrandID(ctx, sqlc.ListNormalProductWithDistributeInfosByBrandIDParams{
		Created:        pagerPtr.Ts,
		BrandID:        brandID,
		ProductGroupID: ptr.ProductGroupID,
		IsKeywordEmpty: isKeywordEmpty,
		Keyword:        keywordLike,
		Offset:         pagerPtr.Offset,
		Limit:          pagerPtr.Limit,
	})
	if err != nil {
		return
	}
	ptrs = s.MapListNormalProductWithDistributeInfoRowEntityToPtr(rows)
	return
}

// ListNormalProductWithDistributeInfoPtrsOfBrandByProductIDs
func (s *ProductServiceImp) ListNormalProductWithDistributeInfoPtrsOfBrandByProductIDs(ctx context.Context, q *sqlc.Queries, brandID int64, productIDs []int64) (ptrs []*sqlc.ListNormalProductWithDistributeInfosByBrandIDAndProductIDsRow, err error) {

	rows, err := q.ListNormalProductWithDistributeInfosByBrandIDAndProductIDs(ctx, sqlc.ListNormalProductWithDistributeInfosByBrandIDAndProductIDsParams{
		BrandID:    brandID,
		ProductIDs: productIDs,
	})
	if err != nil {
		return
	}
	ptrs = s.MapListNormalProductWithDistributeInfosByBrandIDAndProductIDsRowEntityToPtr(rows)
	return
}

// ListNormalProductWithDistributeInfoPtrsOfDistributor
func (s *ProductServiceImp) ListNormalProductWithDistributeInfoPtrsOfDistributor(ctx context.Context, q *sqlc.Queries, distributorPtr *sqlc.BrandDistributor, pagerPtr *util.Pager, ptr *ListNormalProductWithDistributeInfoPtrsParam) (total int64, ptrs []*sqlc.ListNormalProductWithDistributeInfosByBrandIDRow, err error) {
	if distributorPtr.Status != string(sqlc.EmRecordStatusNormal) {
		err = fmt.Errorf("分销者不可用")
		return
	}
	brandID := distributorPtr.BrandID
	return s.ListNormalProductWithDistributeInfoPtrsOfBrand(ctx, q, brandID, pagerPtr, ptr)
}
